//
//  XYRefresh.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/3.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
enum XYRefreshState: Int {
    
    case Normal = 0
    case Pulling = 1
    case Freshing = 2
}
let refreshHeight:CGFloat = 50
class XYRefresh: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.frame.size = CGSizeMake(kSCREENWITH, refreshHeight)
        self.frame.origin.y = -self.frame.size.height
        setUpUI()
    }
    // 给外界设置状态提供的借口
    var oldRefreshState: XYRefreshState = .Normal
    weak var scrollView: UIScrollView?

    var refreshState: XYRefreshState = .Normal {
                didSet {
            switch refreshState {
            case .Pulling:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                self.messageLabel.text = "松手释放"
            case.Normal:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicatorView.stopAnimating()
                // 只有从刷新状态到默认状态m,才要把多出的滑动减回去
                if oldRefreshState == .Freshing {
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top = contentInset.top - refreshHeight
                        self.scrollView?.contentInset = contentInset
                    })
                }
            case.Freshing:
                // 开始动画
                indicatorView.startAnimating()
                arrowIcon.hidden = true
                messageLabel.text = "正在加载"
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top = contentInset.top + refreshHeight
                    self.scrollView?.contentInset = contentInset
                })
                // 发送某个状态所在产生的事件
                sendActionsForControlEvents(.ValueChanged)
            }
            // 记录状态
            oldRefreshState = refreshState
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpUI() {
        backgroundColor = UIColor.yellowColor()
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        // 添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    override func willMoveToSuperview(newSuperview: UIView?) {
       super.willMoveToSuperview(newSuperview)
        // 将父控件tableView 强转为scrollView  
        if let scrollview = newSuperview as? UIScrollView {
            self.scrollView = scrollview
            // 添加通知观察者
            scrollview.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            // 根据父控件的宽度设置自己的宽度
            self.frame.size.width = scrollview.frame.size.width
        }
    }
    // 通知观察的回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 判断当前控件是否全部显示出来
        let contentInsetTop = scrollView!.contentInset.top
        // 完全显示的条件
        let conditionValue = -contentInsetTop - refreshHeight
        if scrollView!.dragging {
            if scrollView!.contentOffset.y <= conditionValue && refreshState == .Normal {
                refreshState = .Pulling
             
            }else if scrollView!.contentOffset.y > conditionValue && refreshState == .Pulling {
                refreshState = .Normal
               
            }
        }else{
            
            // 用户松手
            // 判断当前是否是 `松手就刷新` 状态，如果是，就去刷新
            if refreshState == .Pulling {
                // 如果当前用户已松手，并且当前控件全部显示出来(松手就去刷新的状态，.Pulling)
                refreshState = .Freshing
                print("进入正在刷新的状态")
            }
        }
    }
    // 懒加载控件
    // 箭头图标
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 显示当前状态的 label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    // 刷新中的状态控件
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    // 外部借口
    func endRefreshing() {
        
        refreshState = .Normal
    }
    deinit{
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
